<template>
  <el-container>
    <el-header  style="padding-top: 0px;padding-bottom: 0px;height: 40px;background-color: #fff;
    border-bottom: 1px solid #e6e6e6;">
			<div class="left-panel">
					<label style="font-size: 14px;margin-left: 5px;">新增帮助</label>
			</div>
			<div class="right-panel">
				<fsButton ref="button" plain size="small" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
			</div>
		</el-header>
    <el-main style="padding: 0px;background-color: #fff;padding-top: 20px;">
    <template #default>

          <el-row :gutter="80" style="margin-left: 0px;margin-right: 0px;">
            <el-col :lg="24">
              <el-form :model="form" :rules="button_rules" ref="dialogForm" label-width="80px" label-position="left">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="form.name" clearable placeholder="名称"></el-input>
                </el-form-item>
                <el-form-item label="上级" prop="parentLevelCode">
				   <ex-selector code="SysHelpCenter" :model="form" prop="parentLevelCode" :isicon="true"></ex-selector>
                </el-form-item>
                <el-form-item label="类型" prop="type">
					        <ex-radio-group v-model="form.type" dict-code="HELPTYPE" button></ex-radio-group>
                </el-form-item>
                <el-form-item label="公告内容" prop="content" style="height: 300px;overflow-y: auto;" class="editorcontent">
                  <!--el-input v-model="form.noticeContent" clearable placeholder="公告内容"></el-input-->
                  <vue-ueditor-wrap v-model="form.content"
                          editor-id="editor"
                          :config="editorConfig"
                          :editorDependencies="['ueditor.config.js','ueditor.all.js']"
                          />
                </el-form-item>
                <!--el-form-item label="附件" prop="attachFile">

    <el-upload
                 v-model:file-list="form.attachFile"
                 list-type="picture-card"
                 class="avatar-uploader"
                 limit="1"
                 show-file-list="true"
                 :on-exceed="handleExceed"
                 :before-upload="beforeUpload"
                 :on-success="filehandleSuccess"
                 :on-remove="handleRemove"
                 :on-preview="handlePictureCardPreview"
                 :http-request="submitUpload"
                 :auto-upload="true"
      >
        <el-icon>
          <component is="el-icon-plus">上传附件</component>
        </el-icon>
      </el-upload>

				        </el-form-item-->
                <el-form-item label="排序" prop="orderWeight">
                <el-input v-model="form.orderWeight" clearable placeholder="排序"></el-input>
                </el-form-item>

              </el-form>

            </el-col>
          </el-row>
          <div style="flex: auto;text-align: center;margin-bottom: 20px;">
            <el-button plain type="primary" @click="save" :loading="loading">保 存</el-button>
            <el-button plain type="warning" @click="reset" :loading="loading">重 置</el-button>

          </div>

    </template>
    <template #footer>

    </template>
    </el-main>
  </el-container>
</template>

<script>
import scIconSelect from '@/components/scIconSelect'
import ExRelTable from "@/components/exRelTable/index.vue";
import ExRadioGroup from "@/components/exRadioGroup/index.vue";
import tool from "@/utils/tool";
import exDialog from '@/components/exDialog';
import BaseTemplate from "@/utils/baseTemplate";
import ExSelector from "@/components/exSelector/index.vue";
import router from "@/router";
import useTabs from "@/utils/useTabs";
//import tool from '@/utils/tool';

export default {
  computed: {
  },
  emits: ['success'],
  components: {
    ExSelector,
	  ExRadioGroup,
    ExRelTable,
    scIconSelect,
    exDialog
  },
  props: {
    help: {
      type: Object, default: () => {
      }
    },
  },
  data() {
    return {
      headers: {},
      uploadApi: this.$API.common.upload.url,
      activeName: 'base',
      visible: false,
      title:"",
      isCreate:"0",
      form: {
        id: "",
        name: "",
        parentLevelCode:"",
        mainCategoryCode:"",
        noticeContent: "",
        externalCode:"",
        description: "",
        type:"",
        attachFile:"",
        attachFileJSON:"",
      },

      button_rules: {
        name: [
          {required: true, message: "请输入名称", trigger: "blur"},
        ],
        type: [
          {required: true, message: "请选择类型", trigger: "blur"},
        ],
      },
      loading: false,
      oldForm: null,
      editorConfig: {
        // 后端服务地址，后端处理参考
        // https://open-doc.modstart.com/ueditor-plus/backend.html
        serverUrl: process.env.VUE_APP_API_BASEURL+'/console/ueditor/server',
        // serverUrl: this.$API.system.help.findById.url,
        UEDITOR_HOME_URL: '/static/UEditor/',
        UEDITOR_CORS_URL: '/static/UEditor/',
    }
    }
  },
  watch: {},
  async mounted() {
  //const Authorization = store.getters.access_token
  //let token = tool.cookie.get("TOKEN");
  //  console.log(token);
   // this.headers = { Authorization: token };
   //this.uploadApi=`${config.API_URL}/console/fileOss/upload`;
    //alert(uploadApi);
    let minioServerUrl = await this.$TOOL.minioServerUrl();
    //console.log(minioServerUrl);
    localStorage.setItem("minioServerUrl",minioServerUrl);
  },
  async created() {
	  //如果是通过跳转过来的，标签的名称设置为跳转后的标题
	  let route = router.currentRoute.value;
	  if (route.meta) {
		  this.title = route.meta.title;
	  }
	  console.log(this.$route.params.key);
	  let routeParams = this.$store.state.routeParams[this.$route.params.key];
	  console.log(11111);
	  console.log(routeParams);
	  if (routeParams) {
		  if (routeParams.title) {
			  this.title = routeParams.title;
		  }
		  if (routeParams.fixedParams) {
			  if (routeParams.fixedParams.id) {
				  console.log(routeParams.fixedParams.id);
				  this.form.id = routeParams.fixedParams.id;
				  await this.getDataByQueryDto();
			  }
			  if (routeParams.fixedParams.id) {

			  } else {
				  this.isCreate = '1';
			  }
		  }

		  this.form.entityName = this.$CONSTANT.entity.SysHelpCenter.name;
		  this.oldForm = Object.assign({}, this.form);

	  }
  },
	methods: {
    async initData() {
	  //this.helpOptions = await this.$cache.tree.options(this.$API.system.help.treeData);
    },
    async getDataByQueryDto() {
      console.log(this.form.id);
			//let rsp = await this.$API.system.notice.findById.post({id: this.form.id});
      let rsp = await this.$API.system.help.findById.post({id: this.form.id});
			if (rsp.code === 2000 && rsp.data) {
        this.form=rsp.data;

			}
		},
    relHandler(relMap) {
      if (!this.form.relMaps) {
        this.form.relMaps = {};
      }
      for (let key in relMap) {//清空旧的数据
        this.form.relMaps[key] = {};
      }
      //重新赋值新数据
      Object.assign(this.form.relMaps, relMap);
    },
    //显示
    open(entity) {
      this.form = Object.assign({}, entity);
      this.oldForm = Object.assign({}, this.form);
      this.visible = true;
      this.activeName = "base";
	  this.initData();
    },
    reset() {
      this.form = Object.assign({}, this.oldForm);
		for(let ref in this.$refs){
			try {
				this.$refs[ref].refresh();
			}catch (e){
			}
		}
    },
    //保存
    async save() {
      let valid = await BaseTemplate.validate(this,this.$refs.dialogForm);
      if (valid) {

        try {
          console.log(this.form);
         if(this.form.type=="" || this.form.type==" "){
          this.$message.warning("请选择类型")
          return;
         }
          this.loading = true
          var res;
          if (this.form.id) {
            res = await this.$API.system.help.edit.post(this.form)
          } else {
            res = await this.$API.system.help.add.post(this.form)
          }
          if (res.code === 2000) {

            this.$message.success(this.$t("code."+res.code));
			      this.$emit('success');
            this.visible = false;
			      this.$store.dispatch("commit",this.form.entityName);
            if (!this.form.id) {
              useTabs.close();
            }
          } else {
            this.$message.warning(res.message)
          }
        } finally {
          this.loading = false
        }
      }
    },
    handleSuccess(file) {

      console.log(file);
      const data = file.data;
      this.form.attachFile=data;
      //数据、逻辑处理
    },
    beforeUpload(file) {

// this.column.fileType = "image/png";
if (this.column.fileType && (!file.type || !this.column.fileType.includes(file.type))) {
  this.$message.warning({message: this.$t("common.upload_type_limit", {type: this.column.fileType})});
  return false;
}
if (this.column.maxLength) {
  let fileSize = this.column.maxLength * 1024 * 1024;
  if (file.size >= fileSize) {
    this.$message.warning({message: this.$t("common.upload_filesize_limit", {filesize: this.column.maxLength})});
    return false;
  }
}
return true;
},
handleExceed(file, files) {
  if(files!=null){
    this.$message.warning({message: this.$t("common.upload_count_limit", {limit: files.length})});
  }
},
filehandleSuccess(response, uploadFile, uploadFiles) {
// console.log("handleSuccess",response,uploadFile,uploadFiles);
},
handleRemove(uploadFile, uploadFiles) {
// console.log("handleRemove",uploadFile,uploadFiles);
if (this.form.attachFileJSON.length === 0) {
  this.form.attachFileJSON = '';
} else {
  this.form.attachFileJSON = '';
}

},
async handlePictureCardPreview(uploadFile) {
	let serverUrl = await tool.minioServerUrl();
	if (uploadFile.type.includes("image")) {
		this.dialogImageUrl = serverUrl + uploadFile.realUrl;
		this.dialogVisible = true;
	} else {
		this.$message.warning({message: this.$t("common.file_can_not_preview")});
	}
},
async submitUpload(content) {
	let serverUrl = await tool.minioServerUrl();
let fd = new FormData();
fd.append("file", content.file);
let rsp = await this.$API.common.upload.post(fd, {});
if (rsp.code === 2000) {
  let currentFile = {
    name: content.file.name,
    type: content.file.type ? content.file.type : content.file.name.substring(content.file.name.lastIndexOf(".") + 1),
    size: content.file.size,
    realUrl: rsp.data,
    url: serverUrl + rsp.data,
  };
  if (!content.file.type.includes("image")) {
    currentFile.url = "./img/404.png";
  }
  alert(currentFile);

  //this.model[this.tempCode][this.model[this.tempCode].length - 1] = currentFile;
 // this.model[this.column.code] = JSON.stringify(this.model[this.tempCode]);
}
},
download(file){
this.$TOOL.file.open(file.realUrl,true,file.name);
},

  }
}
</script>

<style scoped>
h2 {
  font-size: 17px;
  color: #3c4a54;
  padding: 0 0 30px 0;
}

[data-theme="dark"] h2 {
  color: #fff;
}

</style>
